package top.lanscarlos.ashcraft.service;

import com.sun.istack.NotNull;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lanscarlos.ashcraft.pojo.Cart;
import top.lanscarlos.ashcraft.pojo.CartItem;
import top.lanscarlos.ashcraft.pojo.Commodity;
import top.lanscarlos.ashcraft.repository.CartRepository;
import top.lanscarlos.ashcraft.repository.CommodityRepository;

import java.util.List;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.service
 *
 * @author Lanscarlos
 * @since 2022-05-26 21:29
 */
@Service
public class CartService {
    @Autowired
    private CartRepository repository;
    @Autowired
    private SessionFactory sessionFactory;

    public Object query(int userId) {
        return repository.query(userId);
    }

    /**
     * 建议使用其他方法
     * */
    @Deprecated
    public Cart modify(
            int cartId,
            int commodityId,
            @NotNull String operation,
            int amount
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            List<CartItem> items = cart.getItems();
            Commodity commodity = session.get(Commodity.class, commodityId);

            int itemIndex = -1; // item 索引
            CartItem item = null;
            // 查询购物车内是否已有该商品的对象
            for (int i=0; i<items.size(); i++) {
                if (commodityId == items.get(i).getCommodity().getId()) {
                    itemIndex = i;
                    item = items.get(i);
                    break;
                }
            }
            switch (operation) {
                case "add":
                    // 若为空则
                    if (item != null) {
                        item.setAmount(item.getAmount() + amount);
                        session.update(item);
                    } else {
                        item = new CartItem(commodity);
                        item.setAmount(amount);
                        items.add(item);
                        session.persist(item);
                    }
                    session.update(cart);
                    transaction.commit();
                    return cart;
                case "remove":
                    if (item == null) return cart;
                    items.remove(itemIndex);
                    session.delete(item);
                    session.update(cart);
                    transaction.commit();
                    return cart;
                case "amount":
                    if (item == null) return cart;
                    int newAmount = item.getAmount() + amount;
                    if (newAmount <= 1) {
                        // 数量不允许小于 1
                        newAmount = 1;
                    } else if (newAmount > commodity.getStorage()) {
                        newAmount = commodity.getStorage();
                    }
                    item.setAmount(newAmount);
                    session.update(item);
                    session.update(cart);
                    transaction.commit();
                    return cart;
            }
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return null;
    }

    public Cart addItem(
            int cartId,
            int commodityId
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            Commodity commodity = session.get(Commodity.class, commodityId);
            CartItem item = null;

            System.out.println("cartId -> " + cartId);

            // 遍历查询是否存在相应的 item
            for (CartItem it : cart.getItems()) {
                if (commodity.getId() == it.getCommodity().getId()) {
                    item = it;
                    break;
                }
            }

            if (item == null) {
                // 未加入购物车
                item = new CartItem(commodity);
                cart.getItems().add(item);
                session.persist(item);
                session.update(cart);
            } else {
                // 已在购物车内
                item.setAmount(item.getAmount() + 1);
                item.setTotalPrice(item.getTotalPrice() + commodity.getPrice());
                session.update(item);

                // 修正总价
                if (item.isSelected()) {
                    cart.setTotalPrice(cart.getTotalPrice() + commodity.getPrice());
                    session.update(cart);
                }
            }
            transaction.commit();
            return cart;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }

    public Cart removeItem(
            int cartId,
            int itemId
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            CartItem item = session.get(CartItem.class, itemId);
            if (item == null) return cart;

            // 删除
            cart.getItems().remove(item);
            cart.setTotalPrice(cart.getTotalPrice() - item.getTotalPrice());
            session.delete(item);
            session.update(cart);
            transaction.commit();
            return cart;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }

    public Cart increaseAmount(
            int cartId,
            int itemId
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            CartItem item = session.get(CartItem.class, itemId);
            if (item.getAmount() >= item.getCommodity().getStorage()) return cart;

            // 添加数量
            item.setAmount(item.getAmount() + 1);
            item.setTotalPrice(item.getTotalPrice() + item.getCommodity().getPrice());
            if (item.isSelected()) {
                cart.setTotalPrice(cart.getTotalPrice() + item.getCommodity().getPrice());
            }
            session.update(item);
            session.update(cart);
            transaction.commit();
            return cart;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }

    public Cart decreaseAmount(
            int cartId,
            int itemId
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            CartItem item = session.get(CartItem.class, itemId);
            if (item.getAmount() <= 1) return cart;

            // 减少数量
            item.setAmount(item.getAmount() - 1);
            item.setTotalPrice(item.getTotalPrice() - item.getCommodity().getPrice());
            if (item.isSelected()) {
                cart.setTotalPrice(cart.getTotalPrice() - item.getCommodity().getPrice());
            }
            session.update(item);
            session.update(cart);
            transaction.commit();
            return cart;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }

    public Cart select(
            int cartId,
            int itemId,
            boolean selected
    ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Cart cart = null;
        try {
            cart = session.get(Cart.class, cartId);
            double totalPrice = cart.getTotalPrice();
            if (itemId <= 0) {
                totalPrice = 0.0;
                // 全选
                for (CartItem item : cart.getItems()) {
                    item.setSelected(selected);
                    session.update(item);
                    if (selected) {
                        totalPrice += item.getTotalPrice();
                    }
                }
            } else {
                CartItem item = session.get(CartItem.class, itemId);
                item.setSelected(selected);
                session.update(item);
                if (selected) {
                    totalPrice += item.getTotalPrice();
                } else {
                    totalPrice -= item.getTotalPrice();
                }
            }
            cart.setTotalPrice(totalPrice);
            session.update(cart);
            transaction.commit();
            return cart;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return cart;
    }
}
